package com.crm.business.examine.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.crm.business.admin.service.AdminMessageService;
import com.crm.business.admin.service.AdminService;
import com.crm.business.crm.service.ICrmContractService;
import com.crm.business.crm.service.ICrmCustomerService;
import com.crm.business.crm.service.ICrmReFundService;
import com.crm.business.crm.service.ICrmReceivablesService;
import com.crm.business.examine.mapper.ExamineCcMapper;
import com.crm.business.examine.service.ExamineCcService;
import com.crm.business.examine.service.IExamineRecordService;
import com.crm.common.crm.entity.PO.CrmContract;
import com.crm.common.crm.entity.PO.CrmCustomer;
import com.crm.common.crm.entity.PO.CrmReceivables;
import com.crm.common.crm.entity.PO.CrmRefund;
import com.crm.common.examine.constant.ExamineEnum;
import com.crm.common.examine.entity.BO.ExamineCCBo;
import com.crm.common.examine.entity.PO.Examine;
import com.crm.common.examine.entity.PO.ExamineCC;
import com.crm.common.examine.entity.PO.ExamineRecord;
import com.crm.common.ka.core.common.CrmCommonEnum;
import com.crm.common.ka.core.feign.admin.entity.AdminMessageBO;
import com.crm.common.ka.core.feign.admin.entity.SimpleDept;
import com.crm.common.ka.core.feign.admin.entity.SimpleRole;
import com.crm.common.ka.core.feign.admin.entity.SimpleUser;
import com.crm.business.servlet.BaseServiceImpl;
import com.crm.business.utils.UserUtil;
import com.crm.common.utils.spring.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.crm.common.ka.core.feign.admin.entity.AdminMessageEnum.CRM_REFUND_CC;

@Service
public class ExamineCcServiceImpl extends BaseServiceImpl<ExamineCcMapper, ExamineCC> implements ExamineCcService {


    @Autowired
    private AdminService adminService;
    @Override
    public ExamineCC addExamineCc(ExamineCCBo ccBo) {

        ExamineCC cc=new ExamineCC();
        cc.setExamineId(ccBo.getExamineId());
        cc.setFlowId(ccBo.getFlowId());
        cc.setRoleId(JSONArray.toJSONString(ccBo.getRoleId()));
        cc.setDeptId(JSONArray.toJSONString(ccBo.getDeptId()));
        cc.setUserId(JSONArray.toJSONString(ccBo.getUserId()));
        cc.setFieldStr(JSONArray.toJSONString(ccBo.getFieldList()));
        cc.setType(ccBo.getType());
        cc.setCreateTime(new Date());
        cc.setUpdateTime(new Date());
        cc.setCreateUserId(Integer.valueOf(UserUtil.getUserId().toString()));
        cc.setUpdateUserId(Integer.valueOf(UserUtil.getUserId().toString()));
        boolean b = save(cc);
        if (b){
            return cc;
        }
        return null;
    }

    @Override
    public Integer updateExamineCc(ExamineCCBo ccBo) {
        ExamineCC cc=new ExamineCC();
//        cc.setId(ccBo.getId());
        cc.setExamineId(ccBo.getExamineId());
        cc.setRoleId(JSONArray.toJSONString(ccBo.getRoleId()));
        cc.setDeptId(JSONArray.toJSONString(ccBo.getDeptId()));
        cc.setUserId(JSONArray.toJSONString(ccBo.getUserId()));
        cc.setType(ccBo.getType());
        cc.setUpdateTime(new Date());
        cc.setUpdateUserId(Integer.valueOf(UserUtil.getUserId().toString()));
        boolean b = saveOrUpdate(cc);
        if (b){
            return 1;
        }
        return 0;
    }

    @Override
    public ExamineCC selectExamineCCById(Integer id) {
        ExamineCC cc = this.getById(id);
        return cc;
    }

    @Override
    public boolean deleteExamineCCById(Integer id) {
        return this.removeById(id);
    }

    @Override
    public ExamineCC selectExamineCCByExamineId(Integer examineId,Integer flowId) {
        LambdaQueryWrapper<ExamineCC> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExamineCC::getExamineId,examineId);
        wrapper.eq(ExamineCC::getFlowId,flowId);
        ExamineCC one = this.getOne(wrapper);
        if (!Optional.ofNullable(one).isPresent()){
            return null;
        }
        if (one.getType()== CrmCommonEnum.CrmCcEnum.部门.getKey()){
            if(StringUtils.isNotBlank(one.getDeptId().trim().substring(1, one.getDeptId().length() - 1))){
                String[] roleIds = one.getDeptId().trim().substring(1, one.getDeptId().length() - 1).split(",");
                List<Integer> ids = Arrays.stream(roleIds).map(str -> Integer.parseInt(str.trim())).collect(Collectors.toList());
                List<SimpleDept> deptList = adminService.queryDeptByIds(ids);
                one.setSimpleDeptList(deptList);
            }
        }
        if (one.getType()==CrmCommonEnum.CrmCcEnum.角色.getKey()){
            if(StringUtils.isNotBlank(one.getRoleId().trim().substring(1, one.getRoleId().length() - 1))){
                String[] roleIds = one.getRoleId().trim().substring(1, one.getRoleId().length() - 1).split(",");
                List<Long> ids = Arrays.stream(roleIds).map(str -> Long.parseLong(str.trim())).collect(Collectors.toList());
                List<SimpleRole> roleList = adminService.queryRoleByIds(ids);
                one.setSimpleRoleList(roleList);
            }
        }
        if (one.getType()==CrmCommonEnum.CrmCcEnum.用户.getKey()){
            if(StringUtils.isNotBlank(one.getUserId().trim().substring(1, one.getUserId().length() - 1))){
                String[] roleIds = one.getUserId().trim().substring(1, one.getUserId().length() - 1).split(",");
                List<Long> ids = Arrays.stream(roleIds).map(str -> Long.parseLong(str.trim())).collect(Collectors.toList());
                List<SimpleUser> userList = adminService.queryUserByIds(ids);
                one.setSimpleUserList(userList);
            }
        }
        if (one.getType()==CrmCommonEnum.CrmCcEnum.数据字段.getKey()){
            String[] fields = one.getFieldStr().trim().substring(1, one.getUserId().length() - 1).split(",");
            List<String> fieldList = Arrays.asList(fields);
            one.setSimpleFieldList(fieldList);
        }
        return one;
    }

    @Override
    public boolean updateExamineCc(ExamineCC ccBo) {
        return this.updateById(ccBo);
    }

    @Override
    public boolean deleteExamineCcByExamineId(Integer examineId) {
        Map<String, Object> map=new HashMap<>();
        map.put("examine_id",examineId);
        int i = this.baseMapper.deleteByMap(map);
        if (i>0){
            return true;
        }
        return  false;
    }

    public List<Long> getUserListByExamineCC(Integer examineId,Integer flowId,Integer recordId){

        LambdaQueryWrapper<ExamineCC> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ExamineCC::getExamineId,examineId);
        wrapper.eq(ExamineCC::getFlowId,flowId);
        ExamineCC cc = this.getOne(wrapper);
        if (!Optional.ofNullable(cc).isPresent()){
            return new ArrayList<>();
        }
        ExamineRecord examineRecord = SpringUtils.getBean(IExamineRecordService.class).lambdaQuery().eq(ExamineRecord::getRecordId,recordId).one();
        List<Long> userIds = new ArrayList<>();
        if (cc.getType()== CrmCommonEnum.CrmCcEnum.角色.getKey()){
            if(StringUtils.isNotBlank(cc.getRoleId().trim().substring(1, cc.getRoleId().length() - 1))){
                String[] roleIds = cc.getRoleId().trim().substring(1, cc.getRoleId().length() - 1).split(",");
                List<Long> ids = Arrays.stream(roleIds).map(str -> Long.parseLong(str.trim())).collect(Collectors.toList());
                long[] idsL = ids.stream().mapToLong(t -> t.longValue()).toArray();
                List<Long> longList = adminService.queryUserListByRoleIds(idsL);
                userIds.addAll(longList);
            }
        }
        if (cc.getType()== CrmCommonEnum.CrmCcEnum.部门.getKey()){
            if(StringUtils.isNotBlank(cc.getDeptId().trim().substring(1, cc.getDeptId().length() - 1))){
                String[] deptIds = cc.getDeptId().trim().substring(1, cc.getDeptId().length() - 1).split(",");
                List<Long> ids = Arrays.stream(deptIds).map(str -> Long.parseLong(str.trim())).collect(Collectors.toList());
                long[] idsL = ids.stream().mapToLong(t -> t.longValue()).toArray();
                List<Long> longList = adminService.queryUserListByDeptIds(idsL);
                userIds .addAll(longList);
            }
        }
        if (cc.getType()== CrmCommonEnum.CrmCcEnum.用户.getKey()){
            if(StringUtils.isNotBlank(cc.getUserId().trim().substring(1, cc.getUserId().length() - 1))){
                String[] ids = cc.getUserId().trim().substring(1, cc.getUserId().length() - 1).split(",");
                List<Long> longList = Arrays.stream(ids).map(str -> Long.parseLong(str.trim())).collect(Collectors.toList());
                userIds.addAll(longList);
            }
        }
        if(cc.getType() == CrmCommonEnum.CrmCcEnum.数据字段.getKey()){
            List<String> longList = JSONArray.parseArray(cc.getFieldStr(),String.class);
            ICrmCustomerService crmCustomerService = SpringUtils.getBean(ICrmCustomerService.class);
            Integer customerId = null;
            //合同
            if(ExamineEnum.CRM_CONTRACT.getType().equals(examineRecord.getLabel())){
                Integer contractId = examineRecord.getTypeId();
                CrmContract contract = SpringUtils.getBean(ICrmContractService.class).getById(contractId);
                if(Optional.ofNullable(contract).isPresent()){
                    if(longList.contains(CrmCommonEnum.ExamineFieldsRoleEnum.销售负责人.getKey()) && Optional.ofNullable(contract.getOwnerUserId()).isPresent()){
                        userIds.add(contract.getOwnerUserId());
                    }
                    if(longList.contains(CrmCommonEnum.ExamineFieldsRoleEnum.营销讲师.getKey()) && Optional.ofNullable(contract.getTeacherId()).isPresent()){
                        userIds.add(contract.getTeacherId());
                    }
                    customerId = contract.getCustomerId();
                }
            }else if(ExamineEnum.CRM_RECEIVABLES.getType().equals(examineRecord.getLabel())){
                //回款
                Integer receivablesId = examineRecord.getTypeId();
                CrmReceivables crmReceivables = SpringUtils.getBean(ICrmReceivablesService.class).getById(receivablesId);
                if(Optional.ofNullable(crmReceivables).isPresent()){
                    if(longList.contains(CrmCommonEnum.ExamineFieldsRoleEnum.销售负责人.getKey()) && Optional.ofNullable(crmReceivables.getOwnerUserId()).isPresent()){
                        userIds.add(crmReceivables.getOwnerUserId());
                    }
                    if(longList.contains(CrmCommonEnum.ExamineFieldsRoleEnum.营销讲师.getKey()) && Optional.ofNullable(crmReceivables.getTeacherId()).isPresent()){
                        userIds.add(crmReceivables.getTeacherId());
                    }
                    customerId = crmReceivables.getCustomerId();
                }
            }else if(ExamineEnum.CRM_REFUND.getType().equals(examineRecord.getLabel())){
                //退款
                Integer refundId = examineRecord.getTypeId();
                CrmRefund crmRefund = SpringUtils.getBean(ICrmReFundService.class).getById(refundId);
                if(Optional.ofNullable(crmRefund).isPresent()){
                    if(longList.contains(CrmCommonEnum.ExamineFieldsRoleEnum.销售负责人.getKey()) && Optional.ofNullable(crmRefund.getOwnerUserId()).isPresent()){
                        userIds.add(crmRefund.getOwnerUserId());
                    }
                    if(longList.contains(CrmCommonEnum.ExamineFieldsRoleEnum.营销讲师.getKey()) && Optional.ofNullable(crmRefund.getTeacherId()).isPresent()){
                        userIds.add(crmRefund.getTeacherId());
                    }
                    if(longList.contains(CrmCommonEnum.ExamineFieldsRoleEnum.退款负责人.getKey()) && Optional.ofNullable(crmRefund.getRefundUserId()).isPresent()){
                        userIds.add(crmRefund.getRefundUserId());
                    }
                    customerId = crmRefund.getCustomerId();
                }
            }
            if(Optional.ofNullable(customerId).isPresent()){
                CrmCustomer crmCustomer = crmCustomerService.getById(customerId);
                if(Optional.ofNullable(crmCustomer).isPresent()){
                    if(longList.contains(CrmCommonEnum.ExamineFieldsRoleEnum.线索创建人.getKey()) && Optional.ofNullable(crmCustomer.getLeadsCreateId()).isPresent()){
                        userIds.add(crmCustomer.getLeadsCreateId());
                    }
                    if(longList.contains(CrmCommonEnum.ExamineFieldsRoleEnum.助教协作人.getKey()) && Optional.ofNullable(crmCustomer.getAssistantUserId()).isPresent()){
                        userIds.add(Long.valueOf(crmCustomer.getAssistantUserId()));
                    }
                }
            }
        }
        return userIds;
    }
}
